$(function(){
    $('#register').on('click',function(){
        $('#loginBox').hide()
        $('#regBox').show()
    })
    $('#log').on('click',function(){
        $('#loginBox').show()
        $('#regBox').hide()
    })

    //正则
    let form = layui.form
    form.verify({
        username:[
            /^[a-zA-Z0-9]{1,10}$/,
            '用户名必须是1-10位字母和数字'
        ],
        password:[
            /^[A-Za-z0-9]{6,15}$/,
            '密码长度必须是6-15位的非空字符串'
        ],
        //函数的提示文本是return出去的
        rePwd:function(value){
            let pwd = $('#regBox [name=password]').val()
            if(value != pwd){
                return '两次密码不一致！'
            }
        }

    })
    //注册
    $('#formReg').on('submit',function(e){
        e.preventDefault()
        axios({
            url:'/api/reguser',
            method:'post',
            data: $(this).serialize()
           
        }).then(res=>{
            //成功回调
            if(res.data.status!=0){
                return layer.msg(res.data.message, {icon: 2})
            }
            layer.msg('恭喜你！'+ res.data.message, {icon: 1})
            //登录成功会清空表单
            $('#formReg')[0].reset()
            //跳转登录页面
            $('#regBox a').click()
        })
    })

    //登录
    $('#formLogin').on('submit',function(e){
        e.preventDefault()
        axios({
            url:'/api/login',
            method:'post',
            data: $(this).serialize()
        }).then(res=>{
            //成功回调
            if(res.data.status!=0){
                return layer.msg(res.data.message, {icon: 2})
            }
            layer.msg('恭喜你！'+ res.data.message, {icon: 1})
            $('#formLogin')[0].reset()
            //保存数据
            localStorage.setItem('token',res.data.token)
            //跳转页面
            location.href = '/index.html'
        })
    })

})